var express = require('express')
const sqlQuery = require('../../../module/sqlQuery')
const { resJsonObject } = require('../../../module/canshu')

var router = express.Router()

/* GET users listing. */
router.get('/', async function (req, res, next) {
  res.render('admin/users/rolelist')
})

router.get('/data', async function (req, res, next) {
  try {
    // keywords 搜索关键词 为空的时候 查询全部
    let { page, limit, keywords = '' } = req.query
    console.log(req.query)

    page = parseInt(page ? page : 1)
    limit = parseInt(limit)
    const results = await sqlQuery(
      'select * from rolelist where rolename like ? limit ?,?',
      ['%' + keywords + '%', (page - 1) * 5, limit]
    )

    // 符合条件的总条数
    const [
      { count_num },
    ] = await sqlQuery(
      'select count(*) as count_num from rolelist where rolename like ?',
      ['%' + keywords + '%']
    )

    res.json(
      resJsonObject({
        code: 0,
        msg: '完成',
        data: {
          arr: Array.from(results),
          count: count_num,
        },
      })
    )
    // res.render('admin/users/userlist',{userlist:results});
  } catch (error) {
    res.json(
      resJsonObject({
        code: 1,
        msg: '获取失败',
        data: {
          error,
        },
      })
    )
  }
})

router.get('/add', (req, res, next) => {
  res.render('admin/users/addRole.ejs')
})

router.post('/add', async (req, res, next) => {
  try {
    let { rolename, rolebrief, authlist } = req.body

    // authlist = JSON.parse(authlist)

    // 1，更新角色表，
    const resultForRoleListTable = await sqlQuery(
      'insert into rolelist (rolename,brief) values (?,?)',
      [rolename, rolebrief]
    )

    // 2，更新角色权限关联表
    const insertId = resultForRoleListTable.insertId

    // // 拼接出多条insert语句，一次执行
    // 貌似现在的方法不让一次执行多个insert语句
    // let sqlRoleAuth = ''
    // authlist.forEach((item) => {
    //   sqlRoleAuth += `insert into role_auth (roleid,authid)
    // values (${parseInt(insertId)},${parseInt(item.value)}); `
    // })

    authlist.forEach(async (item) => {
      await sqlQuery(`insert into role_auth (roleid,authid)
      values (${parseInt(insertId)},${parseInt(item.value)}); `)
    })

    res.json(
      resJsonObject({
        code: 0,
        msg: '添加成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '添加失败',
        data: {
          error,
        },
      })
    )
  }
})

// 用户信息删除
router.post('/delete', async function (req, res, next) {
  // console.log(req.body)
  const { id } = req.body

  try {
    // 用户信息删除（update状态改位为 0 ）
    // const { username, password, email, mobile, roleid } = req.body

    // 要删除角色权限表，该角色下所有的权限信息
    await sqlQuery('delete from role_auth where roleid=?', [parseInt(id)])

    const results = await sqlQuery('delete from rolelist where id=?', [
      parseInt(id),
    ])

    res.json(
      resJsonObject({
        code: 0,
        msg: '删除成功',
      })
    )
  } catch (error) {
    res.json(
      resJsonObject({
        code: 1,
        msg: '删除失败',
        data: {
          error,
        },
      })
    )
  }
})

// 信息界面 编辑
router.get('/edit/:id', async function (req, res, next) {
  let sqlStr = `select * from rolelist where id=?`

  // 获取角色列表
  const results = await sqlQuery(sqlStr, [req.params.id])
  // res.json(results)
  const options = { roleinfo: results[0] }
  res.render('admin/users/editRole.ejs', options)
})

router.post('/edit', async function (req, res, next) {
  try {
    let { roleid, rolename, rolebrief, authlist } = req.body

    // authlist = JSON.parse(authlist)

    // 1，更新角色表，
    const resultForRoleListTable = await sqlQuery(
      'update rolelist set rolename =?, brief=? where id=?',
      [rolename, rolebrief, roleid]
    )

    // 2，更新角色权限关联表

    // 先删除原有的该角色的权限信息
    await sqlQuery('delete from role_auth where roleid=?', [roleid])

    // 添加新的角色权限信息
    authlist.forEach(async (item) => {
      await sqlQuery(`insert into role_auth (roleid,authid)
      values (${parseInt(roleid)},${parseInt(item.value)}); `)
    })

    res.json(
      resJsonObject({
        code: 0,
        msg: '添加成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '添加失败',
        data: {
          error,
        },
      })
    )
  }
})

module.exports = router
